package org.charles.android.easlogger;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemProperties;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class EasloggerActivity extends Activity implements OnClickListener {
    private Button btnStartLog;
    private Button btnStopLog;
    private Intent mIntent;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStartLog = (Button) findViewById(R.id.start_log);
        btnStopLog = (Button) findViewById(R.id.stop_log);
        btnStartLog.setOnClickListener(this);
        btnStopLog.setOnClickListener(this);
        mIntent = new Intent(this, EasloggerService.class);
    }

    @Override
    public void onClick(View v) {
        if (v == btnStartLog) {
            log("EAS log requested");
            // Send out broadcast
            openEasLog();
            //Set System Property
            System.setProperty("log.tag.Serializer", "VERBOSE");
            log("Process Prop: " + System.getProperty("log.tag.Serializer"));
            setSystemProperty();
            //Start service
            startService(mIntent);
        } else if (v == btnStopLog) {
            log("stop logging");
            stopService(mIntent);
//            log("Process prop: " + System.getProperty("log.tag.Serializer"));
//            log("System prop: " + SystemProperties.get("log.tag.Serializer"));
//            log("is logable: " + Log.isLoggable("Charles_TAG", Log.VERBOSE));
//            SystemProperties.set("log.tag.Serializer", "CHARLES");
//            System.setProperty("log.tag.Serializer", "CHARLES");
        }
    }

    private void setSystemProperty() {
//        SystemProperties.set("log.tag.Serializer", "VERBOSE");
        try{
            Runtime.getRuntime().exec("setprop log.tag.Serializer VERBOSE");
        }catch (Exception e) {
            // TODO: handle exception
            log(e.toString());
        }
    }

    private void openEasLog() {
        Intent gingerIntent = new Intent("android.provider.Telephony.SECRET_CODE",
                Uri.parse("android_secret_code://" + "2010"));
        sendBroadcast(gingerIntent);
        Intent icsIntent = new Intent("android.provider.Telephony.SECRET_CODE",
                Uri.parse("android_secret_code://" + "36245"));
        sendBroadcast(icsIntent);
    }

    private void log(String s) {
        Log.i("Charles_TAG", this.getClass().getSimpleName() + " :: " + s);
    }
}